<template>
  <view class="top-top">
    <top-blank></top-blank>
    <top-common @backPage="backPage" titleContent="请选择报修地点"></top-common>
  </view>
  <view class="content">
    <view class="btns">
      <!-- 选取地点后的确定和取消按钮 -->
      <view @click="back">取消</view>
      <view @click="checkAdd">确定</view>
    </view>

    <!-- 地图部分 -->
    <!-- markers	Array		标记点 -->
    <!-- include-points	Array		缩放视野以包含所有给定的坐标点 -->
    <!-- scale	Number	16	缩放级别，取值范围为3-20 -->

    <map class="mapStyle" :show-location="true" :latitude="latitude" :longitude="longitude" :markers="markers"
         @tap="tap" :include-points="markers" :scale="17" />
    <!-- <view id="container"></view> -->

    <!-- 搜索框 -->
    <view class="inputCon">
      <view class="searchView">
        <text class="iconfont icon-sousuo"></text>
        <input type="text" placeholder="搜索地点" v-model="searchWords" confirm-type="search" @confirm="searchFn" />
        <text @click="cancel">取消</text>
      </view>
    </view>
    <!-- 地点列表部分 -->
    <view class="list">
      <view class="item" v-for="(item,index) in dataTips" :key="item.id" @click="select(item,index)"
            :class="selectIndex==index?'active':''">
        <view class="name">{{item.name}}</view>
        <view class="address">{{item.district || ''}}{{item.address || ''}}</view>
      </view>
    </view>
  </view>
</template>

<script>
import {
  getDistrictId
} from '@/api/choosePositionApi.js'
// 引入高德地图api提供的微信小程序的接口
import AMapWX from '../../common/lib/amap-wx.130.js'
import MyStore from '@/store/index.js'
// 创建地图
var myAmapFun = new AMapWX({
  key: 'da27f51049da04469506ea411eca842f'
});
console.log("创建了高德地图myAmapFun");
export default {
  data() {
    return {
      selectIndex: 0,
      selectAddr: '',
      searchWords: "",
      id: 0, // 使用 marker点击事件 需要填写id
      title: 'map',
      latitude: "",
      longitude: "",
      markers: [{ //标记---选点数组
        id: 0, // 添加id属性
        latitude: "",
        longitude: "",
        width: 25,
        height: 25,
        iconPath: '../../static/image/repair-position/position.png'
      }],
      dataTips: [] ,//当前位置的地点列表
      InitializeAdcodeValue:0,
    }
  },
  onLoad(options) {
    //获取当前位置
    this.init();

    // 获取周边的POI（信息点）
    myAmapFun.getPoiAround({
      iconPath: '../../static/logo.png',
      iconPathSelected: '../../static/logo.png',
      success: (data) => {
        this.dataTips = data.poisData;
      },
      fail: (info) => {
        console.log(info)
      }
    })
  },
  methods: {
    // 选择地点后，将选取的地点传递到前一个页面中
    checkAdd() {
      // console.log("打印所选地区的adcode",this.selectAddr.adcode);
      this.$store.dispatch('setAddrAsync', this.selectAddr);

      //在数据库查询区域id
      getDistrictId(this.selectAddr.adcode);
      setTimeout(function() {
        if (MyStore.getters.getDistrictId == -1) {
          uni.showToast({
            icon: 'none',
            title: "该地点不在维修服务区,请重新选择"
          })

          return;
        }

        let choose = MyStore.getters.getChoosePosition;
        if (choose == 1) {
          uni.redirectTo({
            url: '/components/RepairInformation/RepairInformation'
          });
        }

        if (choose == 2) {
          uni.redirectTo({
            url: '/pages/equipment-maintenance/equipment-maintenance'
          });
        }


      }, 1000)
    },
    back() {
      let chooseFlag = MyStore.getters.getChoosePosition;
      if(chooseFlag == 1){
        uni.redirectTo({
          url: '/components/RepairInformation/RepairInformation'
        })
      }else if(chooseFlag == 2){
        uni.redirectTo({
          url:'/pages/equipment-maintenance/equipment-maintenance'
        })
      }
    },
    cancel() {
      if (this.searchWords) {
        this.searchWords = ""; //点击取消，清空搜索框
        myAmapFun.getPoiAround({
          location: this.markers[0].longitude + ',' + this.markers[0].latitude,
          success: (data) => {
            this.dataTips = data.poisData;
          },
          fail: (info) => {
            console.log(info)
          }
        })
      }
    },
    // 根据地址列表中选择某一个地点
    select(item, index) {
      if (!item) {
        return;
      }
      this.selectIndex = index;

      let location = item.location.split(","); //经纬度 location: "113.751764,23.020536"
      this.markers[0].latitude = +location[1];
      this.markers[0].longitude = +location[0];

      let ADcode;
      if(item.adcode === undefined){
        ADcode = this.InitializeAdcodeValue;
      }else{
        ADcode = item.adcode;
      }

      this.selectAddr = {
        address: item.pname ? (item.pname + item.cityname + item.adname + item.address) : (item.district +
            item.address),
        latitude: location[1], //纬度
        longitude: location[0], //经度
        name: item.name, //如：隆江猪脚饭  大标题
        addressMin: item.address, //如：大岭山镇横镇西路340号101室隆江猪脚饭  小标题
        addressDetails: item,
        adcode: ADcode
      };

    },
    // 在地图上点击进行选点，这个选点在地图缩放比例较大时无效，因为精读的问题。
    tap(e) {
      let location = e.detail.longitude + ',' + e.detail.latitude
      myAmapFun.getRegeo({
        location: location, //点击处的经纬度坐标
        success: (data) => { //调用成功的回调函数
          this.selectAddr = {
            address: data[0].regeocodeData.formatted_address, //如"广东省东莞市南城街道东莞市人民政府"
            latitude: e.detail.latitude,
            longitude: e.detail.longitude
          };
          this.latitude = data[0].latitude;
          this.longitude = data[0].longitude;
          this.markers[0].latitude = data[0].latitude;
          this.markers[0].longitude = data[0].longitude;
          myAmapFun.getPoiAround({
            location: data[0].longitude + ',' + data[0].latitude,
            success: (data) => {
              this.dataTips = data.poisData;
            },
            fail: (info) => {
              console.log(info)
            }
          })
        },
        fail: (info) => {
          console.log(info);
        }
      })
    },
    // 根据内容进行检索
    searchFn() {
      myAmapFun.getInputtips({
        keywords: this.searchWords,
        location: '',
        success: (data) => {
          if (data && data.tips) {
            this.dataTips = data.tips; //将搜索结果赋值
          }
        },
        fail: data => {
          console.log(222, data);
        }
      })
    },
    init() {
      //获取定位当前定位信息，如果在服务区，便于刚进入选点功能时就能直接点“确定按钮”
      myAmapFun.getRegeo({
        success: (data) => {
          let res = data[0]
          this.longitude = res.longitude
          this.latitude = res.latitude
          uni.hideLoading();
          this.selectAddr = {
            address: res.name + res.desc,
            latitude: this.latitude, //纬度
            longitude: this.longitude, //经度
            name: res.name, //如：隆江猪脚饭
            addressMin: res.regeocodeData.formatted_address, //如：大岭山镇横镇西路340号101室隆江猪脚饭
            addressDetails: res,
            adcode: res.regeocodeData.addressComponent.adcode,
          };
          this.InitializeAdcodeValue = res.regeocodeData.addressComponent.adcode;
        },
        fail(err) {
          console.log('定位当前位置失败，错误信息', err);
        }
      });
    },
    backPage(){
      let chooseFlag = MyStore.getters.getChoosePosition;
      if(chooseFlag == 1){
        uni.redirectTo({
          url: '/components/RepairInformation/RepairInformation'
        })
      }else if(chooseFlag == 2){
        uni.redirectTo({
          url:'/pages/equipment-maintenance/equipment-maintenance'
        })
      }
    }
  }
}
</script>

<style lang="scss">
.btns {
  position: fixed;
  top: 170rpx;
  left: 0;
  height: 80rpx;
  width: 100%;
  background-color: #333;
  display: flex;
  justify-content: space-between;
  z-index: 10000 !important;

  //按钮view的样式
  view {
    z-index: 12000;
    margin: 10rpx 24rpx 0 24rpx;
    font-size: 30rpx;
    box-sizing: border-box;
    color: #fff;
    height: 60rpx;
    line-height: 60rpx;
    width: 100rpx;
    text-align: center;

    //左侧按钮
    &:first-child {
      background: #4f4f4f;

      &:active {
        background: #747474;
      }
    }

    //右侧按钮
    &:last-child {
      background: #ffb612;

      &:active {
        background: #ffca2a;
      }
    }
  }
}

.content {
  background-color: #333;
  color: #fff;

  .mapStyle {
    margin-top: 5vh;
    z-index: 9;
    width: 100%;
    height: 34vh;
  }

  .list {
    height: calc(60vh - 320rpx);
    overflow-y: auto;
    width: 100%;
    padding: 0 10rpx;
    margin: 0 auto 0;
    padding-bottom: 20rpx;
    position: relative;
    z-index: 0;

    .item {
      border-bottom: 2upx solid #f3f3f3;

      &:last-child {
        border: none;
      }

      .address {
        font-size: 22rpx;
        color: #fff;
        margin: 10upx 0;
      }

      .name {
        font-size: 30rpx;
        color: #fff;
        margin-top: 10rpx;
      }

      &.active {
        .name {
          font-weight: bold;
          color: #e1b517;
        }

        .address {
          color: #e1b517;
        }
      }
    }
  }

  .inputCon {
    background-color: #333;
    margin-top: 50rpx;
    width: 100%;
    position: relative;
    height: 100rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    .searchView {
      width: 702rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      line-height: 60rpx;
      border-radius: 40rpx;
      padding: 0 30rpx;
      box-sizing: border-box;
      background: #f3f3f3;
      font-size: 26rpx;
      color: black;

      .iconfont {
        color: #666;
        margin-right: 20rpx;
      }

      input {
        flex: 1;
      }

      view {
        flex-shrink: 0;
      }

      text{
        color: #333;
      }
    }
  }

}
</style>